// 基础配置
const BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api'
// const BASE_URL = 'http://120.79.70.217:8080/api'
const TIMEOUT = 15000
const requestQueue = new Map()


export const request = (options) => {
  const { url, method = 'GET', data = {}, headers = {} } = options
  const requestKey = `${method}_${url}_${JSON.stringify(data)}`

  // 拦截重复请求
  if (requestQueue.has(requestKey)) {
    return requestQueue.get(requestKey)
  }

  const requestTask = new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url,
      method,
      data,
      header: {
        'Content-Type': 'application/json',
        'Authorization': uni.getStorageSync('token') || '',
        ...headers
      },
      timeout: TIMEOUT,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else {
          reject(handleError(res))
        }
      },
      fail: (error) => reject(handleError(error))
    })
  })

  requestQueue.set(requestKey, requestTask)
  requestTask.finally(() => requestQueue.delete(requestKey))
  return requestTask
}

// 错误处理函数
const handleError = (error) => {
  const errorMap = {
    401: '身份验证失败',
    403: '没有操作权限',
    404: '资源不存在',
    500: '服务器错误'
  }
  
  return {
    code: error.statusCode || -1,
    message: error.errMsg || errorMap[error.statusCode] || '网络异常',
    data: error.data
  }
}